package com.entertainment.ticketing.config;

import com.entertainment.ticketing.dto.ApiResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 对所有@RestController的返回进行包装
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ApiResponse) {
            return body; // 已是统一结构
        }

        if (body instanceof ResponseEntity<?> entity) {
            Object inner = entity.getBody();
            ApiResponse<Object> wrapped = (inner instanceof ApiResponse)
                    ? (ApiResponse<Object>) inner
                    : ApiResponse.success(inner);
            HttpStatusCode statusCode = entity.getStatusCode();
            HttpHeaders headers = entity.getHeaders();
            return new ResponseEntity<>(wrapped, headers, statusCode);
        }

        // 统一包装普通返回
        return ApiResponse.success(body);
    }
}